﻿#include "AppSettingsModelParser.h"

AppSettingsModelParser::AppSettingsModelParser()
    : IModelParser<AppSettingsModel>()
{

}

QString AppSettingsModelParser::toString(const AppSettingsModel &model)
{
    QJsonObject root;

    root["general"] = generalToJson(model.general);
    root["log"] = logToJson(model.log);
    root["cmd"] = cmdToJson(model.cmd);
    root["code"] = codeToJson(model.code);

    setLastError("");
    // 创建 JSON 文档并转换为字符串
    QJsonDocument doc(root);
    return doc.toJson(QJsonDocument::Indented);
}

AppSettingsModel AppSettingsModelParser::parseFromJson(const QJsonObject &json)
{
    AppSettingsModel settings;
    settings.general = parseGeneral(json["general"].toObject());
    settings.log = parseLog(json["log"].toObject());
    settings.cmd = parseCmd(json["cmd"].toObject());
    settings.code = parseCode(json["code"].toObject());

    setLastError("");
    return settings;
}

GeneralSettingsModel AppSettingsModelParser::parseGeneral(const QJsonObject &json)
{
    GeneralSettingsModel general;
    general.language = json["language"].toString("zh_CN");
    general.background_imgae = json["background_imgae"].toString("");
    general.show_guide = json["show_guide"].toBool(true);

    return general;
}

LogSettingsModel AppSettingsModelParser::parseLog(const QJsonObject &json)
{
    LogSettingsModel log;
    log.maxline = json["maxline"].toInt(9001);
    QJsonArray filters = json["tag_filter"].toArray();
    log.tag_filter.clear();
    for (auto item : filters) {
        log.tag_filter.push_back(static_cast<TlvTag>(item.toInt()));
    }

    return log;
}

CmdSettingsModel AppSettingsModelParser::parseCmd(const QJsonObject &json)
{
    CmdSettingsModel cmd;
    cmd.default_loop = json["default_loop"].toInt(-1);

    return cmd;
}

CodeSettingsModel AppSettingsModelParser::parseCode(const QJsonObject &json)
{
    CodeSettingsModel code;
    code.showmsg_top = json["showmsg_top"].toBool(false);

    return code;
}

QJsonObject AppSettingsModelParser::generalToJson(const GeneralSettingsModel &general)
{
    QJsonObject generalObj;
    generalObj["language"] = general.language;
    generalObj["background_imgae"] = general.background_imgae;
    generalObj["show_guide"] = general.show_guide;

    return  generalObj;
}

QJsonObject AppSettingsModelParser::logToJson(const LogSettingsModel &log)
{
    QJsonObject logObj;
    logObj["maxline"] = log.maxline;
    QJsonArray filters;
    for (TlvTag tag: log.tag_filter) {
        filters.append(QJsonValue(tag));
    }
    logObj["tag_filter"] = filters;

    return  logObj;
}

QJsonObject AppSettingsModelParser::cmdToJson(const CmdSettingsModel &cmd)
{
    QJsonObject cmdObj;
    cmdObj["default_loop"] = cmd.default_loop;

    return  cmdObj;
}

QJsonObject AppSettingsModelParser::codeToJson(const CodeSettingsModel &code)
{
    QJsonObject codeObj;
    codeObj["showmsg_top"] = code.showmsg_top;

    return  codeObj;
}
